///////////////////////////////////////////////////////////////////////
//  CS 3715 (Winter 2012), Final Project                      		 //
//  Program File Name: FMP.js 			      	                  	 //
//       Student Name: Jonathan Hart-Wall, Kenny Hardiman            //
//         Login Name: jcwhw1, kch004                                //
//              MUN #: 200933455, 200930253    						 //
///////////////////////////////////////////////////////////////////////

/*
 * submit(evt) function
 * starts sendLocations(evt) 
 */
function submit(evt) {
	sendLocations(evt)
}

/*
 * initForms() function Creates var form from contents of 'theform' onclick of
 * form, start submit() command
 */
function initForms() {
	var form = document.getElementById('theform')
	form.fmp.onclick = submit;
}

/*
 * sendLocations(evt) function that sends XML, and resets page with Banner
 * Display HTML
 */
function sendLocations(evt) {
	var choice = document.getElementById("location")
	var location = choice.value

	/*
	 * Creates var url of format localhost:8888/PizzaPlaces?location=location
	 * and creates new XMLHttpRequest req, and opens it to get
	 */
	var url = "PizzaPlaces?location=" + location

	var req = new XMLHttpRequest()
	req.open("Get", url, true)

	/*
	 * When Readystate changes, resets html of Page. Page displays FMP Logo,
	 * text, and then all banners of pizza places in location
	 */
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			var form = evt.target.form
			var body = document.getElementById("content")
			var newcontent = document.createElement('div');
			newcontent.innerHTML = "<form action=\"javascript:void 1\"id=\"theform\">"
					+ "<p align=center><a href=http://localhost:8888><img src=\"images/FMP-Logo.jpg\"></a></p>"
					+ "<p align=\"center\">"
					+ "<span class=\"P\"><b>PIZZA PLACES NEAR YOU</b><br>To select your desired Pizza Place, Click one of the pictures below</span>"
					+ "</p>" + "<div align=center id=\"tablecontent\">"

			var links = recieveLocations(req)
			var images = document.createElement('diva')
			body.innerHTML = ''
			body.appendChild(newcontent.firstChild)

			var tb = document.getElementById('tablecontent')
			for ( var i = 0; i < links.length; i++) {
				var images = document.createElement('div' + i)
				images.innerHTML += links[i]
				tb.appendChild(images.firstChild)
			}
		}
	}
	req.send(null)
}

/*
 * recieveLocations(req) function. Receives XML response from PizzaPlaceServlet.
 * It returns an array rtn, which contains the Name and ImageLinks of all Pizza
 * Places in location.
 */
function recieveLocations(req) {
	var doc = req.responseXML
	var rtn = [];
	var num = doc.getElementsByTagName("Count")[0].textContent

	for ( var i = 0; i < num; i++) {
		var image = doc.getElementsByTagName("ILink")[i].textContent
		var id = doc.getElementsByTagName("Name")[i].textContent
		rtn.push("<p><img src=" + image + " id=\"" + id
				+ "\" onclick=\"submitPP('" + id + "')\"></p>")
	}
	return rtn;
}

/*
 * submitPP(id) function. Sets name to id, and starts sendPP(PP)
 */
function submitPP(id) {
	var name = id
	var PP = document.getElementById(name).id
	sendPP(PP)
}

/*
 * sendPP(PP) function that sends XML and resets page with new Order Page HTML
 * 
 */
function sendPP(PP) {

	/*
	 * Sets pp to PP, and creates var url of format localhost:8888/Order?pp=PP
	 * and creates new XMLHttpRequest req, and opens it to get
	 */
	var pp = PP
	var url = "Order?pp=" + PP

	var req = new XMLHttpRequest()
	req.open("Get", url, true)

	/*
	 * On ReadyState change, Start recievePP(req) and set it to Place and resets
	 * the HTML of Page to display the FMP logo, Multiple check-boxes, that
	 * correspond to toppings, a drop-down menu that lists all the pizza sizes,
	 * an Add Toppings Button and an Add New Pizza Button
	 */
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			var Place = recievePP(req)
			var body = document.getElementById("content")
			var newcontent = document.createElement('div');
			newcontent.innerHTML = "<table width='60%' align=center>"
					+ "<tr><td align=center colspan=2> <a href=http://localhost:8888><img align=center src=\"images/FMP-Logo.jpg\"></a></td></tr>"
					+ "<tr><td class='t1'><p><b>Toppings</b></p>"
					+ "<input type=checkbox id=Pepperoni value=Pepperoni>Pepperoni<br>"
					+ "<input type=checkbox id=Ham value=Ham>Ham<br>"
					+ "<input type=checkbox id=Bacon value=Bacon>Bacon<br>"
					+ "<input type=checkbox id=Sausage value=Sausage>Sausage<br>"
					+ "<input type=checkbox id=GBeef value=GBeef>Ground Beef<br>"
					+ "<input type=checkbox id=XCheese value=XCheese>Extra Cheese<br>"
					+ "<input type=checkbox id=Onion value=Onion>Onion<br>"
					+ "<input type=checkbox id=GPepper value=GPepper>Green Pepper<br>"
					+ "<input type=checkbox id=Olive value=Olive>Olives<br>"
					+ "<input type=checkbox id=HPepper value=HPepper>Hot Peppers<br>"
					+ "<input type=checkbox id=MRoom value=MRoom>Mushrooms<br>"
					+ "<input type=checkbox id=pApple value=pApple>Pineapple<br>"
					+ "<input type=submit id=SubT value=\"Add Toppings\" onclick=COrder() class='in2'><br></td>"
					+ "<td valign=top class=\"t1\"><p><b>Size of Pizza:</b><select class='S2' name=\"Size\" id=\"size\">"
					+ "<option value=\"s\">Small</option>"
					+ "<option value=\"med\">Medium</option>"
					+ "<option value=\"l\">Large</option>"
					+ "<option value=\"xl\">Extra Large</option>"
					+ "<option value=\"pp\">Party Pizza</option></p></select>"
					+ "<p><div id=\"currentpizza\" class = 'p1'>Current Pizza is Empty</div></p></td></tr>"
					+ "<tr><td colspan=2 align=center>"
					+ "<input type=submit id=\"cp\" value=\"Add Pizza to Order\" onclick='anp()' class='in2'>"
			body.innerHTML = ''
			body.appendChild(newcontent.firstChild)
		}
	}
	req.send(null)
}

/*
 * Set var PizzaPlace to empty String. recievePP(req) function that receives XML
 * Response from OrderServlet, and sets PizzaPlace to Name returns PizzaPlace
 */
var PizzaPlace = ""
function recievePP(req) {
	var doc = req.responseXML
	PizzaPlace = doc.getElementsByTagName("Name")[0].textContent
	return PizzaPlace
}

/*
 * COrder(evt) function that adds all checked item values into array
 * toppingsArray. Starts addToPizza(toppingsArray)
 */
function COrder(evt) {
	var toppingsArray = []
	if (document.getElementById("Pepperoni").checked) {
		var top = document.getElementById("Pepperoni").value
		toppingsArray.push(top)
	}
	if (document.getElementById("Ham").checked) {
		var top = document.getElementById("Ham").value
		toppingsArray.push(top)
	}
	if (document.getElementById("Bacon").checked) {
		var top = document.getElementById("Bacon").value
		toppingsArray.push(top)
	}
	if (document.getElementById("Sausage").checked) {
		var top = document.getElementById("Sausage").value
		toppingsArray.push(top)
	}
	if (document.getElementById("GBeef").checked) {
		var top = "Ground Beef"
		toppingsArray.push(top)
	}
	if (document.getElementById("XCheese").checked) {
		var top = "Extra Cheese"
		toppingsArray.push(top)
	}
	if (document.getElementById("Onion").checked) {
		var top = document.getElementById("Onion").value
		toppingsArray.push(top)
	}
	if (document.getElementById("GPepper").checked) {
		var top = "Green Pepper"
		toppingsArray.push(top)
	}
	if (document.getElementById("Olive").checked) {
		var top = document.getElementById("Olive").value
		toppingsArray.push(top)
	}
	if (document.getElementById("HPepper").checked) {
		var top = "Hot Pepper"
		toppingsArray.push(top)
	}
	if (document.getElementById("MRoom").checked) {
		var top = "Mushroom"
		toppingsArray.push(top)
	}
	if (document.getElementById("pApple").checked) {
		var top = "Pineapple"
		toppingsArray.push(top)
	}

	addToPizza(toppingsArray)
}

/*
 * Set topings to empty array addToPizza(toppingsArray) function that adds all
 * checked toppings to div class with id 'currentpizza', and adds html to
 * display them.
 */
var toppings = []
function addToPizza(toppingsArray) {
	var or = document.getElementById('currentpizza')
	var topping = toppingsArray
	toppings = toppingsArray

	or.innerHTML = ""
	var header = document.createElement('ListHead')
	header.innerHTML = "<p><u>Current Pizza Toppings</u></p>"
	or.appendChild(header.firstChild)
	for ( var i = 0; i < topping.length; i++) {
		var tops = document.createElement('div' + i)
		tops.innerHTML += "<p class='p1' style='margin-left:20px'>Topping "
				+ (i + 1) + ": " + topping[i] + "</p>"
		or.appendChild(tops.firstChild)
	}
}

/*
 * anp() function that resets the HTML of Page to display the FMP logo, Multiple
 * check-boxes, that correspond to toppings, a drop-down menu that lists all the
 * pizza sizes, an Add Toppings Button and an Add New Pizza Button
 */

function anp() {
	psize = document.getElementById('size').value
	var body = document.getElementById("content")
	var newcontent = document.createElement('div');
	newcontent.innerHTML = "<table width='60%' align=center>"
			+ "<tr><td align=center colspan=3> <a href=http://localhost:8888><img align=center src=\"images/FMP-Logo.jpg\"></a></td></tr>"
			+ "<tr><td class='t1'><p><b>Toppings</b></p>"
			+ "<input type=checkbox id=Pepperoni value=Pepperoni>Pepperoni<br>"
			+ "<input type=checkbox id=Ham value=Ham>Ham<br>"
			+ "<input type=checkbox id=Bacon value=Bacon>Bacon<br>"
			+ "<input type=checkbox id=Sausage value=Sausage>Sausage<br>"
			+ "<input type=checkbox id=GBeef value=GBeef>Ground Beef<br>"
			+ "<input type=checkbox id=XCheese value=XCheese>Extra Cheese<br>"
			+ "<input type=checkbox id=Onion value=Onion>Onion<br>"
			+ "<input type=checkbox id=GPepper value=GPepper>Green Pepper<br>"
			+ "<input type=checkbox id=Olive value=Olive>Olives<br>"
			+ "<input type=checkbox id=HPepper value=HPepper>Hot Peppers<br>"
			+ "<input type=checkbox id=MRoom value=MRoom>Mushrooms<br>"
			+ "<input type=checkbox id=pApple value=pApple>Pineapple<br>"
			+ "<input type=submit id=SubT value=\"Add Toppings\" onclick=COrder() class='in2'><br></td>"
			+ "<td valign=top class=\"t1\"><p><b>Size of Pizza:</b><select class='S2' name=\"Size\" id=\"size\">"
			+ "<option value=\"s\">Small</option>"
			+ "<option value=\"med\">Medium</option>"
			+ "<option value=\"l\">Large</option>"
			+ "<option value=\"xl\">Extra Large</option>"
			+ "<option value=\"pp\">Party Pizza</option></p></select>"
			+ "<p><div id=\"currentpizza\" class = 'p1'>Current Pizza is Empty</div></p></td>"
			+ "<td valign=top class=\"t1\"><p><div id=\"currentorder\" class='p1'></div></p></td></tr>"
			+ "<tr><td colspan=3 align=center>"
			+ "<input type=submit id=\"cp\" value=\"Add Pizza to Order\" onclick='anp()' class='in2'>"
			+ "<input type=submit id=\"order\" value=\"Confirm Order\" onclick='sendOrder()' class='in2'></td></tr>"
	body.innerHTML = ''
	body.appendChild(newcontent.firstChild)
	ato(psize)
}

 /*
	 * Sets var dictkeys to empty array Sets var dict to empty Object Sets var
	 * num to 0
	 */
var dictkeys = []
var dict = {}
var num = 0

/*
 * ato(size) function that adds the current order to the currentorder div class,
 * that dispalys the order on the HTML page.
 */
function ato(psize) {
	var size = psize
	dictkeys.push(num)
	var pizza = toppings
	pizza.push(size)
	pizza.reverse()
	dict[num] = pizza

	var co = document.getElementById('currentorder')
	co.innerHTML = ""

	var head = document.createElement('head')
	head.innerHTML = "<u>Current Order</u><br>"
	co.appendChild(head.firstChild)

	/*
	 * for loop to print the current order. It scans dict using keys from
	 * dictkeys, and prints corresponding attributes. Increase num by 1 after
	 * every pass.
	 */
	for ( var i = 0; i < dictkeys.length; i++) {
		var length = dict[dictkeys[i]].length
		var print = dict[dictkeys[i]]
		var tops = ""
		for ( var j = 1; j < length; j++) {
			var PizzaSize = print[0]
			tops += " " + print[j]
		}

		if (PizzaSize == 's') {
			var header = document.createElement('ListHead')
			header.innerHTML = "<p><b>Small Pizza</b></p>"
			co.appendChild(header.firstChild)
		}
		if (PizzaSize == 'med') {
			var header = document.createElement('ListHead')
			header.innerHTML = "<p><b>Medium Pizza</b></p>"
			co.appendChild(header.firstChild)
		}
		if (PizzaSize == 'l') {
			var header = document.createElement('ListHead')
			header.innerHTML = "<p><b>Large Pizza</b></p>"
			co.appendChild(header.firstChild)
		}
		if (PizzaSize == 'xl') {
			var header = document.createElement('ListHead')
			header.innerHTML = "<p><b>Extra Large Pizza</b></p>"
			co.appendChild(header.firstChild)
		}
		if (PizzaSize == 'pp') {
			var header = document.createElement('ListHead')
			header.innerHTML = "<p><b>Party Pizza</b></p>"
			co.appendChild(header.firstChild)
		}
		var plist = document.createElement('Plist')
		plist.innerHTML = "<p style='margin-left:20px'>Toppings:" + tops
				+ "</p>"
		co.appendChild(plist.firstChild)
	}
	num = num + 1
}

/*
 * sendOrder() function that sends XMLHttpREquest to PizzaServlet
 */
function sendOrder() {
	
	/*
	 * Creates var url, and creates new XMLHttpRequest req, and sends url of
	 * format localhost:8888/Pizza?pizzaplace=Pizzaplace&order=pizzaSize+numTops
	 */
	var url = "Pizza?pizzaplace=" + PizzaPlace + "&order="
	var tempURL = ""
	for ( var i = 0; i < dictkeys.length; i++) {
		var length = dict[dictkeys[i]].length
		var print = dict[dictkeys[i]]
		var numTop = print.length - 1
		tempURL += print[0] + "+" + numTop + "+"
	}

	var addURL = tempURL.substring(0, (tempURL.length - 1))
	url += addURL

	var req = new XMLHttpRequest()
	req.open("Get", url, true)

	/**
	 * On ReadyState change, sets det to recieveOrder(req)t restes the HTML to
	 * display the Associated information of the Pizza Place, the cost of order,
	 * taxes, delivery charge, and Total cost of order.
	 */
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			var det = recieveOrder(req)
			var body = document.getElementById("content")
			var newcontent = document.createElement('FinalDiv');
			newcontent.innerHTML = "<table width=\"60%\" align=center><tr><td align=\"center\" colspan=2><a href=http://localhost:8888><img src=\"images/FMP-Logo.jpg\"></a></td></tr>"
					+ "<tr><td class=\"t1\"><b>Estimated Order Cost</b>"
					+ "<br>"
					+ det[5]
					+ "x Pizza(s): "
					+ det[8]
					+ "<br>Taxes: "
					+ det[6]
					+ "<br>Delivery Charge: 4.00</td>"
					+ "<td rowspan=\"2\" valign=top class=\"t1\"><b>Store Info</b><br>Name: "
					+ det[0]
					+ "<br>Address: "
					+ det[1]
					+ "<br>Phone Number: "
					+ det[2]
					+ "<br>Open at: "
					+ det[3]
					+ "<br>Closed at: "
					+ det[4]
					+ "</td></tr>"
					+ "<tr><td class=\"t1\"><b>Total Cost: "
					+ det[7]
					+ "</b></td></tr></table>"
			body.innerHTML = ''
			body.appendChild(newcontent.firstChild)
		}
	}

	req.send(null)
}

/**
 * recieveOrder(req) function that receives XML Response from PizzaServlet.
 * Creates varaibles for PPName, Address, PhoneNumber, OTime, CTime, Tax,
 * OrderPrice, OriPrice, and adds them to arry ord.
 */
function recieveOrder(req) {
	var doc = req.responseXML
	var ord = []
	var name = doc.getElementsByTagName("PPName")[0].textContent
	ord.push(name)
	var add = doc.getElementsByTagName("Address")[0].textContent
	ord.push(add)
	var pn = doc.getElementsByTagName("PhoneNumber")[0].textContent
	ord.push(pn)
	var ot = doc.getElementsByTagName("OTime")[0].textContent
	ord.push(ot)
	var ct = doc.getElementsByTagName("CTime")[0].textContent
	ord.push(ct)
	var np = doc.getElementsByTagName("NumPizza")[0].textContent
	ord.push(np)
	var tax = doc.getElementsByTagName("Tax")[0].textContent
	ord.push(tax)
	var op = doc.getElementsByTagName("OrderPrice")[0].textContent
	ord.push(op)
	var orip = doc.getElementsByTagName("OriPrice")[0].textContent
	ord.push(orip)
	return ord
}